export default function createHandlersMiddleware(handlers = []) {
  return middlewareAPI => next => action => {
    const { meta = {} } = action
    const actionHandler = Array.find(
      handlers.concat(meta.handlers || []),
      h => h.type === action.type,
    )
    const beforeHandler = actionHandler && actionHandler.beforeHandler
    const afterHandler = actionHandler && actionHandler.afterHandler

    if (beforeHandler) {
      beforeHandler(middlewareAPI, action)
    }

    const result = next(action)

    if (afterHandler) {
      afterHandler(middlewareAPI, action)
    }

    return result
  }
}
